package cn.edu.service.impl;

import cn.edu.mapper.StockMapper;
import cn.edu.pojo.Stock;
import cn.edu.service.StockServiceRedis;
import cn.edu.service.StockServiceRedisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.ma
 * @since 2022/12/8 16:09
 **/
@Service
public class StockServiceRedissonImpl implements StockServiceRedisson {
    @Resource
    private StockMapper stockMapper;
    @Resource
    private RedissonClient redissonClient;
    @Override
    public String decrement(Integer id) {
        RLock lock = redissonClient.getLock("stock::" + id);
        lock.lock(30,TimeUnit.SECONDS);
        try {
            Stock stock = stockMapper.selectById(id);
            if (stock != null) {
                if (stock.getStock() > 0) {
                    stock.setStock(stock.getStock() - 1);
                    stockMapper.updateById(stock);
                    System.out.println("修改库存数量成功，剩余库存为：" + stock.getStock());
                    return "修改库存数量成功，编号为" + id + "的商品剩余库存为：" + stock.getStock();
                }
            }
            System.out.println("编号为" + id + "的商品剩余库存不足");
            return "编号为" + id + "的商品剩余库存不足";
        }finally {
            lock.unlock();
        }
    }
}
